package net.xdclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.intercepto.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.model.UserDO;
import net.xdclass.mapper.UserMapper;
import net.xdclass.request.LoginRequest;
import net.xdclass.request.RegisterRequest;
import net.xdclass.service.NotifyService;
import net.xdclass.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xdclass.utils.CommonUtil;
import net.xdclass.utils.JWTUtil;
import net.xdclass.utils.JsonData;
import net.xdclass.vo.UserVo;
import org.apache.catalina.User;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cx
 * @since 2022-11-01
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public JsonData reisger(RegisterRequest registerRequest) {
        boolean checkCode = false;
        //校验验证码
        if (StringUtils.isNotBlank(registerRequest.getMail())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISER, registerRequest.getMail(), registerRequest.getCode());

        }
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(registerRequest, userDO);
        userDO.setCreateTime(new Date());
        userDO.setSlogan("cx的签名");
        // 设置密码
        //1.生成秘钥串
        userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        //2.密码加盐处理
//        String cryptPwd = Md5Crypt.apr1Crypt(registerRequest.getPwd(), userDO.getSecret());
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(), userDO.getSecret());
        userDO.setPwd(cryptPwd);
        userDO.setPwd(cryptPwd);
        //账号唯一性检查
        if (checkUniqe(userDO.getMail())) {
            int rows = userMapper.insert(userDO);
            log.info("rows:{}", rows, userDO.toString());
            //用户注册初始化福利信息
            userReisgerInitTask(userDO);
            return JsonData.buildSuccess();
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
        }
    }

    /**
     * 用户登录
     *
     * @param loginRequest
     * @return
     */
    @Override
    public JsonData login(LoginRequest loginRequest) {
        List<UserDO> userDOList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", loginRequest.getMail()));
        if (userDOList != null && userDOList.size() == 1) {
            //已注册
            UserDO userDO = userDOList.get(0);
            String md5Crypt = Md5Crypt.md5Crypt(loginRequest.getPwd().getBytes(), userDO.getSecret());
            //若相等则登录成功
            if (md5Crypt.equals(userDO.getPwd())) {
                //登录成功 生成token
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO,loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);

            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }

        } else {
            //未注册
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    @Override
    public UserVo selectUserDetil() {

        LoginUser loginUser=LoginInterceptor.threadLocal.get();
        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id", loginUser.getId()));
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userDO,userVo);
        return  userVo;
    }


    //TODO 账号唯一性检查
    private boolean checkUniqe(String mail) {
        QueryWrapper queryWrapper = new QueryWrapper<UserDO>().eq("mail", mail);
        List<UserDO> userDOList = userMapper.selectList(queryWrapper);
        return userDOList.size() > 0 ? false : true;
    }

    private void userReisgerInitTask(UserDO userDO) {
        //TODO 用户注册初始化福利信息
    }
}
